<script setup>
import { ref, onMounted, defineProps, toRefs, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  sendSmsCodeApi,
  sendRobotMessageApi,
  uploadFilesApi,
} from "@/request/api";
import { useI18n } from "vue-i18n";
const { t, locale } = useI18n();

const formRef = ref();
const loading = ref(false);
const labelWidth = ref("80px");
const smsText = ref("sendVerificationCode");
const times = ref(null);
const messageId = ref("");
const caseInfoVisible = ref(false);
const collectNoError = ref("");
const caseNoError = ref("");
const regCaseNo = /^[a-zA-Z0-9]{1,5}$/; // 不超过5位, 不包含中文, 不可有空格与特殊字符
const regCollectNo = /^[a-zA-Z0-9\-]{1,20}$/; // 不超过20位, 可包含横杆(-), 不包含中文, 不可有空格与特殊字符
const wordOpt = [
  { text: "suiZhongCase", value: "穗仲案字第", en: "Sui Zhong Case No." },
  { text: "suiZhongInternetCase", value: "穗仲网案字第", en: "Sui Zhong Internet Case No." },
  { text: "suiZhongZhongCase", value: "穗仲中案字第", en: "Sui Zhong Zhong Case No." },
  { text: "suiZhongGuanCase", value: "穗仲莞案字第", en: "Sui Zhong Guan Case No." },
];
let form = ref({
  name: "",
  idType: "身份证",
  idNumber: "",
  email: "",
  phone: "",
  verifyCode: "",
  guid: "",
  letterType: "1",
  letterContents: "",
  caseNo: "",
});
const fileList = ref([]);
let caseInfo = ref({
  caseType: "2",
  caseYear: new Date().getFullYear().toString(),
  caseWord: t("suiZhongCase"),
  caseNo: "",
  collectNo: "",
});

onMounted(async () => {});

watch(
  () => locale.value,
  (val, oldVal) => {
    if (val === "en") {
      labelWidth.value = "136px";
      formRef.value?.clearValidate();
    } else {
      labelWidth.value = "80px";
      formRef.value?.clearValidate();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

watch(
  () => form.value.letterType,
  (val, oldVal) => {
    caseInfoVisible.value = val === "0";
  },
  {
    immediate: true,
    deep: true,
  }
);

// 监控案号和收案号的错误提示, 避免两个错误提示同时出现
watch(
  () => caseInfo.value.caseType,
  (val, oldVal) => {
    if(caseInfo.value.caseType === '1') {
      // 案号
      caseInfo.value.caseNo && caseNoChange(caseInfo.value.caseNo);
      collectNoError.value = "";
    } else {
      // 收案号
      caseInfo.value.collectNo && collectNoChange(caseInfo.value.collectNo);
      caseNoError.value = "";
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

const letterTypeChange = (e) => {
  // caseInfoVisible.value = e === "0";
};
const countDown = () => {
  times.value = setInterval(() => {
    if (smsText.value === 0) {
      clearInterval(times.value);
      smsText.value = "sendVerificationCode";
      return;
    } else if (smsText.value === "sendVerificationCode") {
      smsText.value = 59;
    } else {
      smsText.value--;
    }
  }, 1000);
};
const sendSms = () => {
  const { idNumber, phone } = form.value;
  if (!idNumber) {
    ElMessage.warning(t("field_idCard_placeholder"));
    return;
  }
  if (phone) {
    const data = { idCard: idNumber, phone: phone };
    sendSmsCodeApi(data).then((res) => {
      if (res.result === "200" && res.data) {
        countDown();
        form.value.guid = res.data;
        ElMessage.success(t("verificationCodeSent"));
      }
    });
  } else {
    ElMessage.warning(t("beforeProceeding"));
  }
};
const collectNoChange = (e) => {
  caseInfo.value.collectNo = e.replace(/\s+/g, '');
  if (caseInfo.value.collectNo && !regCollectNo.test(caseInfo.value.collectNo)) {
    collectNoError.value = t("field_receivingNo_verify");
  } else {
    collectNoError.value = "";
  }
};
const caseNoChange = (e) => {
  caseInfo.value.caseNo = e.replace(/\s+/g, '');
  if (caseInfo.value.caseNo && !regCaseNo.test(caseInfo.value.caseNo)) {
    caseNoError.value = t("field_caseNo_verify");
  } else {
    caseNoError.value = "";
  }
};
const httpRequest = (e) => {
  // console.log(e, "......httpRequest");
};
const onChange = (e, list) => {
  const isLt10M = e.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.warning(t("field_filesUpload_sizeMax", { size: 10 }));
    list.splice(-1, 1);
    return false;
  }
};
const onExceed = (e) => {
  if (e.length > 3) {
    ElMessage.warning(t("field_filesUpload_max", { size: 3 }));
  }
};
const beforeSubmit = async () => {
  let formData = JSON.parse(JSON.stringify(form.value));
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      if (form.value.letterType === "0") {
        // 案件详情
        if (caseInfo.value.caseType === "2" && !caseInfo.value.collectNo) {
          // 收案号
          ElMessage.warning(t("caseReceivingNo_placeholder"));
          return;
        } else if (
          caseInfo.value.caseType === "2" &&
          caseInfo.value.collectNo &&
          collectNoError.value !== ""
        ) {
          ElMessage.warning(t("field_receivingNo_verify"));
          return;
        } else if(
          caseInfo.value.caseType === "2" &&
          caseInfo.value.collectNo
        ) {
          formData.caseNo = caseInfo.value.collectNo;
        }
        if (caseInfo.value.caseType === "1" && !caseInfo.value.caseNo) {
          // 案号
          ElMessage.warning(t("caseNo_placeholder"));
          return;
        } else if (
          caseInfo.value.caseType === "1" &&
          caseInfo.value.caseNo &&
          caseNoError.value !== ""
        ) {
          ElMessage.warning(t("field_caseNo_verify"));
          return;
        } else if(
          caseInfo.value.caseType === "1" &&
          caseInfo.value.caseNo
        ) {
          formData.caseNo = `${new Date(
            caseInfo.value.caseYear
          ).getFullYear()}-${caseInfo.value.caseNo}`;
          formData.caseType = wordOpt.find(item => item.value === caseInfo.value.caseWord || item.en === caseInfo.value.caseWord).value;
        }
      }

      // console.log(formData, '......formData')
      onSubmit(formData);
    } else {
      console.log("error submit!", fields);
    }
  });
};
const onSubmit = (data) => {
  loading.value = true;

  sendRobotMessageApi(data)
    .then((res) => {
      if (res && (res.code === 0 || res.result === "200")) {
        if(res.data) {
          messageId.value = res.data;
          ElMessage.success(t("messageSent"));
          if (fileList.value.length > 0) {
            uploadFile(res.data);
          } else {
            loading.value = false;
            resetForm();
          }
        } else {
          loading.value = false;
          ElMessage.warning(t("notFoundCase"));
        }
      }
    })
    .catch((err) => {
      loading.value = false;
    });
};
const uploadFile = (id) => {
  let formData = new FormData();
  fileList.value.map((item) => {
    formData.append("files", item.raw);
  });
  formData.append("id", id);

  uploadFilesApi(formData).then((res) => {
    if (res && (res.code === 0 || res.result === "200")) {
      ElMessage.success(t("fileUploaded"));
      loading.value = false;
      fileList.value = [];
      resetForm();
    }
  });
};
const resetForm = () => {
  form.value = {
    name: "",
    idType: "身份证",
    idNumber: "",
    email: "",
    phone: "",
    verifyCode: "",
    guid: "",
    letterType: "1",
    letterContents: "",
    caseNo: "",
  };
  caseInfo.value = {
    caseType: "2",
    caseYear: new Date().getFullYear().toString(),
    caseWord: t("suiZhongCase"),
    caseNo: "",
    collectNo: "",
  };
  // setTimeout(() => {
  //   formRef.value.resetFields();
  // }, 500);
  clearInterval(times.value);
  smsText.value = "sendVerificationCode";
};
</script>

<template>
  <div class="messageDisplay">
    <div class="outBox">
      <div class="formCnt">
        <el-form
          ref="formRef"
          class="form"
          :model="form"
          label-position="left"
          :label-width="labelWidth"
          status-icon
        >
          <el-form-item
            prop="name"
            :label="$t('field_name')"
            :rules="{
              required: true,
              message: $t('field_name_placeholder'),
              trigger: 'blur',
            }"
          >
            <el-input
              v-model.trim="form.name"
              :placeholder="$t('field_name_placeholder')"
            />
          </el-form-item>
          <el-form-item
            prop="idNumber"
            :label="$t('field_idCard')"
            :rules="{
              required: true,
              message: $t('field_idCard_placeholder'),
              trigger: 'blur',
            }"
          >
            <el-input
              v-model.trim="form.idNumber"
              :placeholder="$t('field_idCard_placeholder')"
            />
          </el-form-item>
          <el-form-item
            class="unRequiredItem"
            prop="email"
            :label="$t('field_mailbox')"
            :rules="[
              {
                required: false,
                message: $t('field_mailbox_placeholder'),
                trigger: 'blur',
              },
              {
                pattern:
                  /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
                message: $t('field_mailbox_verify'),
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model.trim="form.email"
              :placeholder="$t('field_mailbox_placeholder')"
            />
          </el-form-item>
          <el-form-item
            prop="phone"
            :label="$t('field_cellphone')"
            :rules="[
              {
                required: true,
                message: $t('field_cellphone_placeholder'),
                trigger: 'blur',
              },
              {
                pattern:
                  /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/,
                message: $t('field_cellphone_verify'),
                trigger: 'blur',
              },
            ]"
          >
            <div class="formPhone">
              <el-input
                v-model.trim="form.phone"
                :placeholder="$t('field_cellphone_placeholder')"
              />
              <el-button
                class="smsBtn"
                type="primary"
                @click="sendSms"
                :disabled="smsText !== 'sendVerificationCode'"
                >{{
                  !isNaN(parseFloat(smsText)) && isFinite(smsText)
                    ? smsText
                    : $t(smsText)
                }}</el-button
              >
            </div>
          </el-form-item>
          <el-form-item
            prop="verifyCode"
            :label="$t('field_verificationCode')"
            :rules="{
              required: true,
              message: $t('field_verificationCode_placeholder'),
              trigger: 'blur',
            }"
          >
            <el-input
              v-model.trim="form.verifyCode"
              :placeholder="$t('field_verificationCode_placeholder')"
            />
          </el-form-item>
          <el-form-item
            prop="letterType"
            :label="$t('field_messageType')"
            :rules="{
              required: true,
              message: $t('field_messageType_placeholder'),
              trigger: 'blur',
            }"
          >
            <el-radio-group
              v-model="form.letterType"
              @change="letterTypeChange"
            >
              <el-radio value="0">{{ $t("field_caseSituation") }}</el-radio>
              <el-radio value="1">{{ $t("field_suggestion") }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <div v-if="caseInfoVisible" class="caseInfo">
            <el-form-item
              class="unRequiredItem"
              prop="letterType"
              :label="$t('numberType')"
            >
              <el-radio-group v-model="caseInfo.caseType">
                <el-radio value="2">{{ $t("caseReceivingNo") }}</el-radio>
                <el-radio value="1">{{ $t("caseNo") }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              class="unRequiredItem"
              v-if="caseInfo.caseType === '2'"
              :label="$t('caseReceivingNo')"
            >
              <el-input
                v-model.trim="caseInfo.collectNo"
                :placeholder="$t('caseReceivingNo_placeholder')"
                @input="collectNoChange"
              />
              <span class="errorText">{{ collectNoError }}</span>
            </el-form-item>
            <div class="caseNoItem" v-if="caseInfo.caseType === '1'">
              <el-date-picker
                class="caseYear"
                v-model="caseInfo.caseYear"
                type="year"
              />
              <el-select class="caseWord" value-key="value" v-model="caseInfo.caseWord">
                <el-option
                  v-for="item in wordOpt"
                  :key="item.value"
                  :label="$t(item.text)"
                  :value="item.value"
                />
              </el-select>
              <el-input
                class="caseNo"
                v-model.trim="caseInfo.caseNo"
                :placeholder="$t('caseNo_placeholder')"
                @input="caseNoChange"
              />
            </div>
            <span class="errorText">{{ caseNoError }}</span>
            <div class="caseNoTips">
              <van-icon class="icon" name="warning" />
              <div class="cnt">
                <div>
                  {{ $t("receivingNoRemark") }}
                </div>
                <div>
                  {{ $t("caseNoRemark") }}
                </div>
              </div>
            </div>
          </div>

          <el-form-item
            prop="letterContents"
            :label="$t('field_message')"
            :rules="{
              required: true,
              message: $t('field_message_placeholder'),
              trigger: 'blur',
            }"
          >
            <el-input
              v-model.trim="form.letterContents"
              :placeholder="$t('field_message_placeholder')"
              type="textarea"
              maxlength="500"
              show-word-limit
              :autosize="{ minRows: 5 }"
            />
          </el-form-item>
          <el-form-item
            class="unRequiredItem"
            prop="uploader"
            :label="$t('field_filesUpload')"
          >
            <el-upload
              class="uploadBox"
              drag
              action="#"
              multiple
              :limit="3"
              accept=".doc,.docx,.pdf,.ppt,.pptx,.xlsx,.xls,image/*"
              v-model:file-list="fileList"
              :http-request="httpRequest"
              :on-change="onChange"
              :on-exceed="onExceed"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                {{ $t("dropToUpload") }}
              </div>
              <template #tip>
                <div class="el-upload__tip tc_f">
                  * {{ $t("field_filesUpload_max", { size: 3 }) }}
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <div class="btn">
              <el-button
                v-loading="loading"
                size="large"
                type="primary"
                @click="beforeSubmit"
                >{{ $t("submitTheMessage") }}</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.messageDisplay {
  color: #fff;
  display: flex;
  align-items: center;
  .outBox {
    width: 460px;
    height: 640px;
    padding: 26px 16px 16px 16px;
    // margin: auto;
    background: url("/public/img/exhibition-bg.png") no-repeat center center;
    -webkit-background-size: 100% 100%;
    -o-background-size: 100% 100%;
    background-size: 100% 100%;
    position: relative;
    .formCnt {
      height: 100%;
      overflow: auto;
      background: #0378de;
      padding: 20px;
      box-sizing: border-box;
      border-radius: 5px;
      .formPhone {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 20px;
      }
      .uploadBox {
        width: 100%;
      }
      .btn {
        width: 100%;
        text-align: left;
      }
      .caseInfo {
        width: 100%;
        margin-bottom: 18px;
        .caseNoItem {
          // padding: 0px 10px 0 25px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 10px;
          margin-bottom: 2px;
          :deep(.el-date-editor.el-input) {
            flex: 2;
          }
          .caseYear {
            width: 110px !important;
            // flex: 2 !important;
          }
          .caseWord {
            // width: 200px;
            flex: 3;
          }
          .caseNo {
            flex: 3;
          }
        }
        .errorText {
          color: var(--el-color-danger);
          font-size: 12px;
          line-height: 1;
          padding-top: 2px;
        }
        .caseNoTips {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          gap: 10px;
          padding: 10px;
          box-sizing: border-box;
          background: #e6f7ff;
          border-radius: 8px;
          margin-top: 24px;
          // margin-left: 80px;
          .icon {
            font-size: 24px;
            color: #1989fa;
          }
          .cnt {
            font-size: 14px;
            color: #333;
          }
        }
        .caseNoError {
          padding: 0 10px;
          color: var(--van-field-error-message-color);
          font-size: var(--van-field-error-message-font-size);
          margin-bottom: 10px;
        }
        .caseInfoDesc {
          padding: 10px;
          box-sizing: border-box;
          .caseInfoDescInner {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            gap: 10px;
            padding: 10px;
            box-sizing: border-box;
            background: #e6f7ff;
            border-radius: 8px;
            .icon {
              font-size: 24px;
              color: #1989fa;
            }
            .cnt {
              font-size: 14px;
              color: #333;
            }
          }
        }
      }
      :deep(.el-form-item__label) {
        color: #fff;
      }
      :deep(.el-radio__label) {
        color: #fff;
      }
      :deep(.el-upload-list__item-name) {
        color: #333;
      }
      :deep(.el-icon--document) {
        color: #333;
      }
    }
    svg {
      font-size: unset;
    }
    // 美化滚动条
    ::-webkit-scrollbar {
      width: 10px;
      height: 10px;
    }

    ::-webkit-scrollbar-track {
      width: 6px;
      background: #0378de;
      -webkit-border-radius: 2em;
      -moz-border-radius: 2em;
      border-radius: 2em;
    }

    ::-webkit-scrollbar-thumb {
      background-color: #0289ce;
      background-clip: padding-box;
      min-height: 28px;
      -webkit-border-radius: 2em;
      -moz-border-radius: 2em;
      border-radius: 2em;
      transition: background-color 0.3s;
      cursor: pointer;
    }

    ::-webkit-scrollbar-thumb:hover {
      background-color: #041c90;
    }
  }
}
</style>
